package c

import (
	"context"
	"errors"
	_const "github.com/flipped-aurora/gin-vue-admin/server/global/const"
	"github.com/flipped-aurora/gin-vue-admin/server/service/im"
	"gorm.io/gorm"
	"strconv"
	"strings" // 添加 strings 包用于字符串处理
	"time"

	"github.com/spf13/cast"

	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
	"github.com/flipped-aurora/gin-vue-admin/server/model/system"
	systemReq "github.com/flipped-aurora/gin-vue-admin/server/model/system/request"
	systemRes "github.com/flipped-aurora/gin-vue-admin/server/model/system/response"
	"github.com/flipped-aurora/gin-vue-admin/server/utils"
	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
	"go.uber.org/zap"
)

type UserApi struct{}

// Register
// @Tags      C端用户
// @Summary   用户注册
// @accept    application/json
// @Produce   application/json
// @Param     data  body      systemReq.Register                                            true  "用户名, 昵称, 密码, 手机号, 年级, 学校, 专业, 学历, 个性签名"
// @Success   200   {object}  response.Response{data=systemRes.SysUserResponse,msg=string}  "用户注册,返回包括用户信息"
// @Router    /user/register [post]
func (b *UserApi) Register(c *gin.Context) {
	uri := "Register"
	var r systemReq.Register
	err := c.ShouldBindJSON(&r)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(r, utils.UserRegisterVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	user := &system.SysUser{
		Username:  r.Username,
		NickName:  r.NickName,
		Password:  r.Password,
		HeaderImg: r.HeaderImg,
		Phone:     r.Phone,
		Email:     r.Email,
		Grade:     r.Grade,
		School:    r.School,
		Major:     r.Major,
		Education: r.Education,
		Signature: r.Signature,
		Openid:    nil,
	}
	userReturn, err := userService.Register(*user)
	var logID = utils.GetLogID(c)
	if err != nil {
		global.GVA_LOG.Warn("注册失败!", zap.String("uri", uri), zap.String("log_id", logID), zap.Error(err))
		response.FailWithMessage(err.Error(), c)
		return
	}

	// 记录注册成功信息
	ip := c.ClientIP()
	userAgent := c.Request.UserAgent()
	loginRecordService.CreateLoginRecord(userReturn.ID, ip, userAgent, true, "注册成功")

	global.GVA_LOG.Info("注册成功！", zap.String("uri", uri), zap.String("log_id", logID))
	response.OkWithDetailed(systemRes.SysUserResponse{User: userReturn}, "注册成功", c)
}

// Login
// @Tags      C端用户
// @Summary   用户登录
// @accept    application/json
// @Produce   application/json
// @Param     data  body      systemReq.Login                                                true  "用户名, 密码"
// @Success   200   {object}  response.Response{data=systemRes.SysUserResponse,msg=string}  "用户登录,返回包括用户信息"
// @Router    /user/login [post]
func (b *UserApi) Login(c *gin.Context) {
	var l systemReq.CLogin
	err := c.ShouldBindJSON(&l)

	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(l, utils.LoginVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	u := &system.SysUser{Phone: l.Phone, Password: l.Password}
	user, err := userService.CLogin(u)
	if err != nil {
		global.GVA_LOG.Error("登陆失败! 手机号不存在或者密码错误!", zap.Error(err))
		response.FailWithMessage("手机号不存在或者密码错误", c)
		return
	}
	if user.Enable != 1 {
		// 记录登录失败信息
		ip := c.ClientIP()
		userAgent := c.Request.UserAgent()
		loginRecordService.CreateLoginRecord(user.ID, ip, userAgent, false, "手机号被禁止登录")

		global.GVA_LOG.Error("登陆失败! 手机号被禁止登录!")
		response.FailWithMessage("手机号被禁止登录", c)
		return
	}
	// 记录登录成功信息
	ip := c.ClientIP()
	userAgent := c.Request.UserAgent()
	loginRecordService.CreateLoginRecord(user.ID, ip, userAgent, true, "登录成功")

	b.TokenNext(c, *user)
}

// TokenNext 登录以后签发jwt
func (b *UserApi) TokenNext(c *gin.Context, user system.SysUser) {
	token, claims, err := utils.LoginToken(&user)
	if err != nil {
		global.GVA_LOG.Error("获取token失败!", zap.Error(err))
		response.FailWithMessage("获取token失败", c)
		return
	}
	// TODO 当前默认使用小程序端获取imtoken，后续开启多端登录改造时，修改逻辑为端需要登录接口传入
	// 获取IM token
	var imToken string
	var imExpire int64
	imToken, imExpire, err = im.IMCommonServiceApp.GetUserToken(context.Background(), strconv.Itoa(int(user.ID)), _const.PlatformIDMiniApp)
	if err != nil { // 不阻塞流程，继续执行
		global.GVA_LOG.Error("获取IM token失败!", zap.Error(err))
	}
	if !global.GVA_CONFIG.System.UseMultipoint {
		utils.SetToken(c, token, int(claims.RegisteredClaims.ExpiresAt.Unix()-time.Now().Unix()))
		response.OkWithDetailed(systemRes.LoginResponse{
			User:      user,
			Token:     token,
			ExpiresAt: claims.RegisteredClaims.ExpiresAt.Unix() * 1000,
			ImToken:   imToken,
		}, "登录成功", c)
		return
	}

	if tokenInfo, err := jwtService.GetRedisJWTWithIMToken(user.Username); err == redis.Nil {
		if err := utils.SetRedisJWTWithIMToken(token, user.Username, imToken, imExpire); err != nil {
			global.GVA_LOG.Error("设置登录状态失败!", zap.Error(err))
			response.FailWithMessage("设置登录状态失败", c)
			return
		}
		utils.SetToken(c, token, int(claims.RegisteredClaims.ExpiresAt.Unix()-time.Now().Unix()))
		response.OkWithDetailed(systemRes.LoginResponse{
			User:      user,
			Token:     token,
			ExpiresAt: claims.RegisteredClaims.ExpiresAt.Unix() * 1000,
			ImToken:   imToken,
		}, "登录成功", c)
	} else if err != nil {
		global.GVA_LOG.Error("设置登录状态失败!", zap.Error(err))
		response.FailWithMessage("设置登录状态失败", c)
	} else {
		// 禁止多点登录时，发现已有登录redis流程，则将旧token放入黑名单
		var blackJWT system.JwtBlacklist
		blackJWT.Jwt = tokenInfo.SystemTokenJWT
		if err := jwtService.JsonInBlacklist(blackJWT); err != nil {
			response.FailWithMessage("jwt作废失败", c)
			return
		}
		if err := utils.SetRedisJWTWithIMToken(token, user.GetUsername(), imToken, imExpire); err != nil {
			response.FailWithMessage("设置登录状态失败", c)
			return
		}
		utils.SetToken(c, token, int(claims.RegisteredClaims.ExpiresAt.Unix()-time.Now().Unix()))
		response.OkWithDetailed(systemRes.LoginResponse{
			User:      user,
			Token:     token,
			ExpiresAt: claims.RegisteredClaims.ExpiresAt.Unix() * 1000,
			ImToken:   imToken,
		}, "登录成功", c)
	}
}

// Logout 用户登出
// @Tags      C端用户
// @Summary   用户登出
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Success   200  {object}  response.Response{msg=string}  "用户登出"
// @Router    /user/logout [post]
func (b *UserApi) Logout(c *gin.Context) {
	// 获取当前token
	token := utils.GetToken(c)

	// 将token加入黑名单
	jwt := system.JwtBlacklist{Jwt: token}
	err := jwtService.JsonInBlacklist(jwt)
	if err != nil {
		global.GVA_LOG.Error("jwt作废失败!", zap.Error(err))
		response.FailWithMessage("jwt作废失败", c)
		return
	}

	// TODO 清除Redis中的用户信息，这里主要是想要把imtoken注销掉，暂不影响业务，需要前端传递用户名(账号)，查询对应的缓存
	//username := utils.GetUsername(c)
	//if global.GVA_CONFIG.System.UseMultipoint {
	//	// 删除Redis中的用户token信息
	//	err = global.GVA_REDIS.Del(context.Background(), username).Err()
	//	if err != nil {
	//		global.GVA_LOG.Error("清除Redis用户信息失败!", zap.Error(err))
	//		// 注意：这里不返回错误，因为登出操作的主要目的是使token失效
	//	}
	//}

	// 清除客户端token
	utils.ClearToken(c)
	response.OkWithMessage("登出成功", c)
}

// GetUserInfo
// @Tags      C端用户
// @Summary   获取用户信息
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Success   200  {object}  response.Response{data=systemRes.UserInfoWithDictResponse,msg=string}  "获取用户信息"
// @Router    /user/getUserInfo [get]
func (b *UserApi) GetUserInfo(c *gin.Context) {
	uuid := utils.GetUserUuid(c)
	token := utils.GetToken(c)
	ReqUser, err := userService.GetUserInfoWithDict(uuid)
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		// 如果是记录不存在错误，返回更明确的错误信息，并建议重新登录
		if errors.Is(err, gorm.ErrRecordNotFound) {
			jwt := system.JwtBlacklist{Jwt: token}
			err = jwtService.JsonInBlacklist(jwt)
			if err == nil {
				response.FailWithMessage("用户信息不存在，请重新登录", c)
				return
			}
		}
		response.FailWithMessage("获取失败", c)
		return
	}
	response.OkWithDetailed(systemRes.UserInfoWithDictResponse{
		User: ReqUser,
	}, "获取成功", c)
}

// SetSelfInfo
// @Tags      C端用户
// @Summary   设置用户信息
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      system.SysUser                                             true  "ID, 用户名, 昵称, 头像链接, 年级, 学校, 专业, 学历, 个性签名"
// @Success   200   {object}  response.Response{data=map[string]interface{},msg=string}  "设置用户信息"
// @Router    /user/setSelfInfo [put]
func (b *UserApi) SetSelfInfo(c *gin.Context) {
	var user systemReq.ChangeUserInfo
	err := c.ShouldBindJSON(&user)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	global.GVA_LOG.Info("SetSelfInfo start", zap.Any("user", user))
	user.ID = utils.GetUserID(c)
	err = userService.SetSelfInfo(system.SysUser{
		GVA_MODEL: global.GVA_MODEL{
			ID: user.ID,
		},
		NickName:  user.NickName,
		HeaderImg: user.HeaderImg,
		Phone:     user.Phone,
		Email:     user.Email,
		Grade:     user.Grade,
		School:    user.School,
		Education: user.Education,
		Signature: user.Signature,
	})
	if err != nil {
		global.GVA_LOG.Error("设置失败!", zap.Error(err))
		response.FailWithMessage("设置失败", c)
		return
	}
	uuid := utils.GetUserUuid(c)
	err = userService.ClearRedisUserInfo(uuid)
	if err != nil {
		global.GVA_LOG.Error("清除缓存失败!", zap.Error(err))
	}
	response.OkWithMessage("设置成功", c)
}

// ChangePassword
// @Tags      C端用户
// @Summary   用户修改密码
// @Security  ApiKeyAuth
// @Produce  application/json
// @Param     data  body      systemReq.ChangePasswordReq    true  "用户名, 原密码, 新密码"
// @Success   200   {object}  response.Response{msg=string}  "用户修改密码"
// @Router    /user/changePassword [post]
func (b *UserApi) ChangePassword(c *gin.Context) {
	var req systemReq.ChangePasswordReq
	err := c.ShouldBindJSON(&req)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(req, utils.ChangePasswordVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	uid := utils.GetUserID(c)
	u := &system.SysUser{GVA_MODEL: global.GVA_MODEL{ID: uid}, Password: req.Password}
	_, err = userService.ChangePassword(u, req.NewPassword)
	if err != nil {
		global.GVA_LOG.Error("修改失败!", zap.Error(err))
		response.FailWithMessage("修改失败，原密码与当前账户不符", c)
		return
	}
	response.OkWithMessage("修改成功", c)
}

// FollowUser
// @Tags      C端用户
// @Summary   关注/取关用户
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      systemReq.FollowUser    true  "被关注者ID"
// @Success   200   {object}  response.Response{data=systemRes.FollowResponse,msg=string}  "关注/取关成功"
// @Router    /user/follow [post]
func (b *UserApi) FollowUser(c *gin.Context) {
	var req systemReq.FollowUser
	err := c.ShouldBindJSON(&req)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	currentUserID := utils.GetUserID(c)
	isFollowed, err := userFollowService.FollowUser(currentUserID, req.FollowedID)
	if err != nil {
		global.GVA_LOG.Error("关注操作失败!", zap.Error(err))
		response.FailWithMessage(err.Error(), c)
		return
	}

	action := "关注"
	if !isFollowed {
		action = "取关"
	}

	response.OkWithDetailed(systemRes.FollowResponse{
		IsFollowed: isFollowed,
	}, action+"成功", c)
}

// WxOneTapRegister
// @Tags      Auth
// @Summary   微信一键注册登录
// @accept    application/json
// @Produce   application/json
// @Param     data  body      systemReq.WxOneTapRegister true  "微信登录参数"
// @Success   200   {object}  response.Response{data=systemRes.LoginResponse,msg=string}  "注册登录成功"
// @Failure   400   {object}  response.Response{msg=string}  "参数缺失或微信验证失败"
// @Failure   500   {object}  response.Response{msg=string}  "系统错误"
// @Router    /user/wx-one-tap-register [post]
func (b *UserApi) WxOneTapRegister(c *gin.Context) {
	// 1.入参解析,参数解析失败或未传入登录code均报错返回
	var req systemReq.WxOneTapRegister
	if err := c.ShouldBindJSON(&req); err != nil || req.LoginCode == "" {
		global.GVA_LOG.Error("参数验证失败", zap.Error(err))
		response.FailWithDetailed(map[string]int{"code": 4001}, "参数缺失", c)
		return
	}

	// 2.校验微信配置
	appid := global.GVA_CONFIG.Wx.Miniapp.Appid
	secret := global.GVA_CONFIG.Wx.Miniapp.Secret
	if appid == "" || secret == "" {
		global.GVA_LOG.Error("微信小程序未配置")
		response.FailWithDetailed(map[string]int{"code": 500}, "系统错误", c)
		return
	}
	// 3.使用loginCode登录
	wxInfo, err := utils.Code2Session(req.LoginCode)
	if err != nil {
		global.GVA_LOG.Error("微信接口调用失败", zap.Error(err))
		response.FailWithDetailed(map[string]int{"code": 4002}, "微信验证失败", c)
		return
	}

	// 4.校验手机登录code是否存在，存在则尝试通过手机号获取用户信息
	// 注意：手机号获取失败不会阻塞登录流程
	var phoneNum string
	if req.PhoneCode != "" {
		phoneInfo, err := utils.GetPhoneNumber(req.PhoneCode)
		if err != nil {
			global.GVA_LOG.Error("微信接口获取手机号失败", zap.Error(err), zap.String("phoneCode", req.PhoneCode))
			// 手机号获取失败，继续登录流程，phoneNum保持为空
		} else {
			phoneNum = phoneInfo.PhoneNumber
			global.GVA_LOG.Info("成功获取手机号", zap.String("phoneNum", phoneNum))
		}
	} else {
		global.GVA_LOG.Info("phoneCode为空，跳过手机号获取")
	}

	// 调用service处理用户注册/登录
	user, err := userService.WxOneTapRegister(wxInfo.OpenID, phoneNum)
	if err != nil {
		global.GVA_LOG.Error("WxOneTapRegister:用户处理失败", zap.Error(err))
		response.FailWithDetailed(map[string]int{"code": 500}, "系统错误", c)
		return
	}

	// 记录注册成功信息
	ip := c.ClientIP()
	userAgent := c.Request.UserAgent()
	loginRecordService.CreateLoginRecord(user.ID, ip, userAgent, true, "注册成功")

	// 生成JWT
	b.TokenNext(c, *user)
}

// GetUserInfoById
// @Tags      C端用户
// @Summary   根据ID获取用户信息（包含关注状态和字典名称）
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     userId  query     uint    true  "用户ID"
// @Success   200     {object}  response.Response{data=systemRes.UserInfoWithDictAndFollowResponse,msg=string}  "获取用户信息成功"
// @Router    /user/getUserInfoById [get]
func (b *UserApi) GetUserInfoById(c *gin.Context) {
	userIDStr := c.Query("userId")
	if userIDStr == "" {
		response.FailWithMessage("用户ID不能为空", c)
		return
	}

	userID, err := strconv.ParseUint(userIDStr, 10, 32)
	if err != nil {
		response.FailWithMessage("用户ID格式错误", c)
		return
	}

	currentUserID := utils.GetUserID(c)
	user, isFollowed, err := userFollowService.GetUserInfoWithFollowStatusAndDict(uint(userID), currentUserID)
	if err != nil {
		global.GVA_LOG.Error("获取用户信息失败!", zap.Error(err))
		response.FailWithMessage("获取用户信息失败", c)
		return
	}

	response.OkWithDetailed(systemRes.UserInfoWithDictAndFollowResponse{
		User:       user,
		IsFollowed: isFollowed,
	}, "获取成功", c)
}

func (b *UserApi) GetFollowList(c *gin.Context) {
	var pageInfo systemReq.GetUserList
	err := c.ShouldBindJSON(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(pageInfo, utils.PageInfoVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	userId := ""
	if len(pageInfo.UserIds) == 0 {
		userId = cast.ToString(utils.GetUserID(c))
	} else {
		userId = cast.ToString(pageInfo.UserIds[0])
	}
	ids, _, err := userService.GetFollowListIds(userId, pageInfo.Page, pageInfo.PageSize)
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
		return
	}
	// 根据userId筛选，就不用再根据page和pageSize筛选了
	pageInfo.UserIds = ids
	list, total, err := userService.GetUserInfoListForC(pageInfo)
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
		return
	}
	response.OkWithDetailed(response.PageResult{
		List:     list,
		Total:    total,
		Page:     pageInfo.Page,
		PageSize: pageInfo.PageSize,
	}, "获取成功", c)

}
func (b *UserApi) GetFollowedList(c *gin.Context) {
	var pageInfo = systemReq.GetUserList{}
	err := c.ShouldBindJSON(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(pageInfo, utils.PageInfoVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	userId := ""
	if len(pageInfo.UserIds) > 0 {
		userId = cast.ToString(pageInfo.UserIds[0]) // 截取第一个
	} else {
		userId = cast.ToString(utils.GetUserID(c))
	}
	ids, _, err := userService.GetFollowedIds(userId, pageInfo.Page, pageInfo.PageSize)
	// 根据userId筛选，就不用再根据page和pageSize筛选了
	pageInfo.UserIds = ids
	list, total, err := userService.GetUserInfoListForC(pageInfo)
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
		return
	}
	response.OkWithDetailed(response.PageResult{
		List:     list,
		Total:    total,
		Page:     pageInfo.Page,
		PageSize: pageInfo.PageSize,
	}, "获取成功", c)

}

// GetMajorCategories 获取专业大类
// @Tags      C端用户
// @Summary   获取专业大类
// @accept    application/json
// @Produce   application/json
// @Success   200  {object}  response.Response{data=[]system.SysDictionaryDetail,msg=string}  "获取专业大类成功"
// @Router    /user/getMajorCategories [get]
func (b *UserApi) GetMajorCategories(c *gin.Context) {
	// 专业字典ID为9
	const majorDictionaryID = 9

	// 直接获取顶级节点，不进行递归查询
	majorCategories, err := dictionaryDetailService.GetTopLevelDictionaryDetails(majorDictionaryID)
	if err != nil {
		global.GVA_LOG.Error("获取专业大类失败!", zap.Error(err))
		response.FailWithMessage("获取专业大类失败", c)
		return
	}

	// 处理专业类名称中的括号备注
	for i := range majorCategories {
		if idx := strings.Index(majorCategories[i].Label, "("); idx > 0 {
			majorCategories[i].Label = majorCategories[i].Label[:idx]
		}
		// 确保Children字段为空
		majorCategories[i].Children = nil
	}

	response.OkWithDetailed(majorCategories, "获取专业大类成功", c)
}

// GetMajorSubcategoriesByParentID 根据父ID获取专业子类数据
// @Tags      C端用户
// @Summary   根据父ID获取专业子类数据
// @accept    application/json
// @Produce   application/json
// @Param     parentID  query     int                                                          true  "父级ID"
// @Success   200       {object}  response.Response{data=[]system.SysDictionaryDetail,msg=string}  "获取专业子类成功"
// @Router    /user/getMajorSubcategoriesByParentID [get]
func (b *UserApi) GetMajorSubcategoriesByParentID(c *gin.Context) {
	// 获取查询参数
	parentIDStr := c.Query("parentID")
	if parentIDStr == "" {
		response.FailWithMessage("父级ID不能为空", c)
		return
	}

	// 转换为uint类型
	parentID, err := strconv.ParseUint(parentIDStr, 10, 32)
	if err != nil {
		response.FailWithMessage("父级ID格式不正确", c)
		return
	}

	// 专业字典ID为9
	const majorDictionaryID = 9

	// 直接获取指定父ID的直接子节点，不进行递归查询
	majorSubcategories, err := dictionaryDetailService.GetDirectChildrenByParentID(majorDictionaryID, uint(parentID))
	if err != nil {
		global.GVA_LOG.Error("获取专业子类失败!", zap.Error(err))
		response.FailWithMessage("获取专业子类失败", c)
		return
	}

	// 处理专业类名称中的括号备注
	for i := range majorSubcategories {
		if idx := strings.Index(majorSubcategories[i].Label, "("); idx > 0 {
			majorSubcategories[i].Label = majorSubcategories[i].Label[:idx]
		}
		// 确保Children字段为空
		majorSubcategories[i].Children = nil
	}

	response.OkWithDetailed(majorSubcategories, "获取专业子类成功", c)
}

// GetMajorDirectoryTree
// @Tags      C端用户
// @Summary   获取专业目录树
// @accept    application/json
// @Produce   application/json
// @Success   200  {object}  response.Response{data=[]system.SysDictionaryDetail,msg=string}  "获取专业目录树成功"
// @Router    /user/getMajorDirectoryTree [get]
func (b *UserApi) GetMajorDirectoryTree(c *gin.Context) {
	// 专业字典ID为9
	const majorDictionaryID = uint(9)

	// 获取完整的级联树形结构
	list, err := dictionaryDetailService.GetFullDictionaryDetailTree(majorDictionaryID)
	if err != nil {
		global.GVA_LOG.Error("获取专业目录树失败!", zap.Error(err))
		response.FailWithMessage("获取专业目录树失败", c)
		return
	}

	// 处理专业类名称中括号内的备注信息
	cleanMajorClassNames(list)

	response.OkWithDetailed(list, "获取专业目录树成功", c)
}

// cleanMajorClassNames 处理专业类名称中括号内的备注信息
func cleanMajorClassNames(nodes []system.SysDictionaryDetail) {
	for i := range nodes {
		// 处理当前节点
		node := &nodes[i]

		// 检查是否有子节点（专业类）
		if len(node.Children) > 0 {
			for j := range node.Children {
				majorClass := &node.Children[j]

				// 移除括号内的备注信息
				if idx := strings.Index(majorClass.Label, "("); idx != -1 {
					majorClass.Label = strings.TrimSpace(majorClass.Label[:idx])
				}

				// 递归处理下一级节点（具体专业）
				if len(majorClass.Children) > 0 {
					cleanMajorClassNames([]system.SysDictionaryDetail{*majorClass})
				}
			}
		}
	}
}

// GetUserIMToken 获取用户的imtoken
func (u *UserApi) GetUserIMToken(c *gin.Context) {
	var req = systemReq.GetUserIMTokenReq{}
	err := c.ShouldBindJSON(&req)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	if req.ID <= 0 {
		req.ID = utils.GetUserID(c)
	}
	token, expires, err := im.IMCommonServiceApp.GetUserToken(c, strconv.FormatUint(uint64(req.ID), 10), req.PlatformID)
	if err != nil {
		global.GVA_LOG.Error("获取用户token失败!", zap.Error(err))
		response.FailWithMessage("获取用户token失败", c)
		return
	}
	response.OkWithDetailed(systemRes.UserIMTokenResponse{
		Token:   token,
		Expires: expires,
	}, "获取成功", c)
}

// MajorAuth
// @Tags      C端用户
// @Summary   用户专业认证
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      systemReq.MajorAuthRequest  true  "用户ID, 专业ID"
// @Success   200   {object}  response.Response{msg=string}  "专业认证成功"
// @Router    /user/major-auth [post]
func (b *UserApi) MajorAuth(c *gin.Context) {
	var req systemReq.MajorAuthRequest
	err := c.ShouldBindJSON(&req)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	err = utils.Verify(req, utils.CustomVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	// 验证请求的用户ID是否为当前登录用户
	currentUserID := utils.GetUserID(c)
	if req.UserID != currentUserID {
		response.FailWithMessage("无权操作其他用户", c)
		return
	}

	err = userService.MajorAuth(req.UserID, req.MajorID)
	if err != nil {
		global.GVA_LOG.Error("专业认证失败", zap.Error(err))
		response.FailWithMessage("专业认证失败", c)
		return
	}
	// 认证成功
	// 在专业认证成功后，异步调用社区模块函数让用户自动加入对应专业社区
	go func(userId uint, majorId int) {
		// 增加重试逻辑
		maxRetries := 3
		for i := 0; i < maxRetries; i++ {
			communityInfo, err := communityService.GetCommunityByMajorID(majorId)
			if err != nil {
				global.GVA_LOG.Error("获取专业对应的社区失败", zap.Error(err), zap.Int("majorId", majorId))
				if i == maxRetries-1 {
					// 最后一次重试失败，记录到错误队列等待人工处理
					//recordFailedCommunityJoin(userId, majorId, err.Error())
				}
				time.Sleep(time.Duration(i*100) * time.Millisecond) // 指数退避
				continue
			}

			if err := communityService.JoinCommunity(userId, communityInfo.ID); err != nil {
				if strings.Contains(err.Error(), "已加入") {
					global.GVA_LOG.Info("用户已加入专业社区", zap.Uint("userId", userId), zap.Uint("communityId", communityInfo.ID))
					break // 已加入不需要重试
				} else {
					global.GVA_LOG.Error("用户加入专业社区失败", zap.Error(err), zap.Uint("userId", userId), zap.Uint("communityId", communityInfo.ID))
					if i == maxRetries-1 {
						//recordFailedCommunityJoin(userId, majorId, err.Error())
					}
					time.Sleep(time.Duration(i*100) * time.Millisecond)
					continue
				}
			}

			global.GVA_LOG.Info("用户成功加入专业社区", zap.Uint("userId", userId), zap.Uint("communityId", communityInfo.ID), zap.String("communityName", communityInfo.Name))
			break
		}
	}(req.UserID, req.MajorID)

	response.OkWithMessage("专业认证成功", c)
}
